<!-- 商品评论  -->
<template>
  <!-- 列表 -->
  <ContentWrap :show-border="false">
    <h3>商品评论</h3>
    <el-row :gutter="10" class="mt-6 mb6">
      <el-col :span="1.5" class="el-btn">
        <el-button
          type="primary"
          color="#3721FF"
          class="add-website-btn"
          @click="handleAddClassification"
        >
          <Icon class="mr-2px" icon="ep:plus" />
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5" class="el-btn">
        <el-button
          type="primary"
          color="#3721FF"
          plain
          class="add-website-btn"
          @click="handleAllDel"
        >
          批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5" class="el-btn">
        <el-button type="default" class="add-website-btn" @click="handleImport">
          <Icon class="mr-2px" icon="ep:download" />
          导入列表
        </el-button>
      </el-col>
      <el-col :span="1.5" class="el-btn">
        <el-button type="default" class="add-website-btn" @click="handleExport">
          <Icon class="mr-2px" icon="ep:upload" />
          导出列表
        </el-button>
      </el-col>
      <el-col :span="15" class="flex text-right">
        <el-button type="default" plain class="add-website-btn" @click="handleSetProduct">
          设置
        </el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="list"
      :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
      class="rounded-lg"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="用户名称" prop="userNickname" />
      <el-table-column label="用户头像" prop="userAvatar">
        <template #default="{ row }">
          <img
            v-if="row.userAvatar"
            class="mr-2 rounded-lg w-38px h-38px"
            :src="row.userAvatar"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column label="评论内容" width="200" prop="content" />
      <el-table-column label="评论图片" width="200">
        <template #default="{ row }">
          <div v-if="row.picUrls.length > 0">
            <div v-for="itm in row.picUrls" :key="itm" class="flex items-center">
              <img class="mr-2 rounded-lg w-38px h-38px" :src="itm" alt="" />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="评论星级" width="160">
        <template #default="{ row }">
          <el-rate v-model="row.scores" disabled />
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="评论时间"
        prop="commentTime"
        width="180"
      />
      <el-table-column align="center" fixed="right" label="操作" class-name="all-button">
        <template #default="{ row }">
          <el-button link type="primary" color="#3721FF" plain @click="openDetail(row.id)">
            编辑
          </el-button>
          <el-button link type="danger" plain @click="handleDelete(row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
  <el-dialog v-model="isComment" width="40%">
    <template #title>
      <div class="drawer-header">
        <div class="flex items-center dot">
          <div class="w-[5px] h-[5px] rounded-1/2 bg-[#3721FF]"></div>
          <span class="ml-2 drawer-title">商品评论</span>
        </div>
      </div>
    </template>
    <el-form
      label-width="100px"
      label-position="left"
      :rules="rules"
      :model="form"
      ref="addCommentRef"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="userNickname">
            <el-input v-model="form.userNickname" placeholder="请输入用户昵称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评论时间" prop="commentTime">
            <el-date-picker
              v-model="form.commentTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="用户内容" prop="content">
        <el-input v-model="form.content" type="textarea" rows="6" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="评论星级" prop="scores">
        <el-rate v-model="form.scores" />
      </el-form-item>
      <el-form-item label="用户头像">
        <UploadImg
          height="80px"
          width="80px"
          class="min-w-80px"
          :limit="1"
          v-model="form.userAvatar"
        />
      </el-form-item>
      <el-form-item label="评论图片">
        <UploadImgs
          height="80px"
          width="80px"
          class="min-w-80px"
          :limit="10"
          v-model="form.picUrls"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isComment = false">取 消</el-button>
        <el-button type="primary" @click="sumitComment">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 正常删除弹窗 -->
  <ComfirmPops
    ref="deletePopsRef"
    :show-icon="true"
    width="500px"
    :show-dot="false"
    type="idTips"
    title="删除"
    :id="delSelected"
    @confirm="getDeletePops"
  >
    <template #content>
      <p>确定删除吗？</p>
    </template>
  </ComfirmPops>
  <Settings ref="settingsRef" />
  <ImportForm ref="importFormRef" @success="getList" />
</template>
<script lang="ts" setup>
import { TabsPaneContext } from 'element-plus'
import ImportForm from './importForm.vue'
import { createImageViewer } from '@/components/ImageViewer'
import { dateFormatter } from '@/utils/formatTime'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import { ProductSpuStatusEnum } from '@/utils/constants'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import Settings from '../settings/index.vue'
const { loadStart, loadDone } = usePageLoading()
import {
  createComment,
  getCommentList,
  updateComment,
  getComment,
  exportComment,
  deleteComment,
  importComment
} from '@/api/comment/index'

defineOptions({ name: 'ProductComment' })
const importFormRef = ref() // 导入弹窗
const deletePopsRef = ref()
const delSelected = ref(0)
const message = useMessage() // 消息弹窗
const route = useRoute() // 路由
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转
const addCommentRef = ref() // 新增属性
const settingsRef = ref() // 设置弹窗

const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
const isAddCopy = ref(false) // 是否复制
const isComment = ref(false) //
const copyId = ref(0) // 复制的ID
const list = ref<ProductSpuApi.Spu[]>([]) // 列表的数据

const form = ref({
  id: null,
  userNickname: '',
  commentTime: '',
  content: '',
  scores: 0,
  userAvatar: '',
  productId: route.query.id,
  picUrls: []
})
// tabs 数据
const tabsData = ref([
  {
    name: '出售中',
    type: 0,
    count: 0
  },
  {
    name: '仓库中',
    type: 1,
    count: 0
  },
  {
    name: '已售罄',
    type: 2,
    count: 0
  },
  {
    name: '警戒库存',
    type: 3,
    count: 0
  },
  {
    name: '回收站',
    type: 4,
    count: 0
  }
])
// 原始数据
const rules = {
  userNickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  commentTime: [{ required: true, message: '请选择评论时间', trigger: 'blur' }],
  content: [{ required: true, message: '请输入用户内容', trigger: 'blur' }],
  scores: [{ required: true, message: '请选择评论星级', trigger: 'blur' }]
}
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  tabType: 0,
  name: '',
  categoryId: undefined,
  productId: route.query.id,
  createTime: undefined
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref

// 搜索关键词
const searchText = ref('')
// 已选中的地区
const selectedRegions = ref([])
const router = useRouter() // 路由
// 设置
const handleSetProduct = () => {
  settingsRef.value.show()
}

const sumitComment = () => {
  form.value.productId = route.query.id
  addCommentRef.value.validate((valid: boolean) => {
    if (valid) {
      if (form.value.scores == 0) {
        message.error('请选择评论星级')
        return
      }
      // 年月日转时间戳
      form.value.commentTime = new Date(form.value.commentTime).getTime()
      if (form.value?.id) {
        updateComment(form.value).then((res) => {
          message.success('修改成功')
          isComment.value = false
          getList()
          resetForm()
        })
      } else {
        createComment(form.value).then((res) => {
          message.success('新增成功')
          isComment.value = false
          getList()
          resetForm()
        })
      }
    }
  })
}
const goSetNavigation = () => {
  router.push({ name: 'SetNavigation' })
}
// 复制
const goCopy = (id: number) => {
  isAddCopy.value = true
  copyId.value = id
}
// 网站分析
const goWebsiteAnalysis = (id: number) => {
  isComment.value = true
}
// 根据搜索词过滤选项
const filteredOptions = (filters) => {
  return filters.filter((item) => item.text.includes(searchText.value))
}
// 清空表单
const resetForm = () => {
  addCommentRef.value?.resetFields()
  form.value.picUrls = []
  form.value.id = null
  form.value.userAvatar = ''
  getList()
}
const handleAddClassification = () => {
  isComment.value = true
  resetForm()
}

/** 查看商品详情 */
const openDetail = (id: number) => {
  getComment({ id: id }).then((res) => {
    form.value = res
    // 时间戳转换年月日时分秒
    let date = res.commentTime
    form.value.commentTime = formatTimestamp(date)
  })
  isComment.value = true
}
function formatTimestamp(timestamp) {
  const date = new Date(timestamp)

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 删除
const getDeletePops = (bool, id: number) => {
  deleteComment([id]).then((res) => {
    message.success('删除成功')
    getList()
  })
}
// 批量选择
const allSelected = ref([])
const handleSelectionChange = (val: any) => {
  allSelected.value = val
}
// 批量删除
const handleAllDel = () => {
  if (allSelected.value.length === 0) {
    message.error('请选择要删除的评论')
    return
  }
  message
    .confirm('确认要删除选中的评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',

      type: 'warning'
    })
    .then(() => {
      allDel()
    })
}
const allDel = () => {
  let ids = allSelected.value.map((item) => item.id)
  const params = new URLSearchParams()
  ids.forEach((id) => params.append('ids', id))
  deleteComment(params.toString().replace(/^ids=/, '')).then((res) => {
    message.success('删除成功')
    getList()
  })
  // getDeletePops(true)
}
// 筛选逻辑
const filterHandler = (value, row) => {
  return selectedRegions.value.includes(row.region)
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getCommentList(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.tabType = tab.paneName as number
  getList()
}

/** 获得每个 Tab 的数量 */
const getTabsCount = async () => {
  const res = await ProductSpuApi.getTabsCount()
  for (let objName in res) {
    tabsData.value[Number(objName)].count = res[objName]
  }
}

/** 添加到仓库 / 回收站的状态 */
const handleStatus02Change = async (row: any, newStatus: number) => {
  try {
    // 二次确认
    const text = newStatus === ProductSpuStatusEnum.RECYCLE.status ? '加入到回收站' : '恢复到仓库'
    await message.confirm(`确认要"${row.name}"${text}吗？`)
    // 发起修改
    await ProductSpuApi.updateStatus({ id: row.id, status: newStatus })
    message.success(text + '成功')
    // 刷新 tabs 数据
    await getTabsCount()
    // 刷新列表
    await getList()
  } catch {}
}

/** 更新上架/下架状态 */
const handleStatusChange = async (row: any) => {
  try {
    // 二次确认
    const text = row.status ? '上架' : '下架'
    await message.confirm(`确认要${text}"${row.name}"吗？`)
    // 发起修改
    await ProductSpuApi.updateStatus({ id: row.id, status: row.status })
    message.success(text + '成功')
    // 刷新 tabs 数据
    await getTabsCount()
    // 刷新列表
    await getList()
  } catch {
    // 异常时，需要重置回之前的值
    row.status =
      row.status === ProductSpuStatusEnum.DISABLE.status
        ? ProductSpuStatusEnum.ENABLE.status
        : ProductSpuStatusEnum.DISABLE.status
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  deletePopsRef.value.show(id)
  delSelected.value = id
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 新增或修改 */
const openForm = (id?: number) => {
  // 修改
  if (typeof id === 'number') {
    push({ name: 'ProductSpuEdit', params: { id } })
    return
  }
  // 新增
  push({ name: 'ProductSpuAdd' })
}
// 导入
const handleImport = () => {
  importFormRef.value.open(route.query.id)
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportComment(queryParams.value)
    download.excel(data, '商品评论列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取分类的节点的完整结构 */
const categoryList = ref() // 分类树
const formatCategoryName = (categoryId: number) => {
  return treeToString(categoryList.value, categoryId)
}

/** 激活时 */
onActivated(() => {
  getList()
})

/** 初始化 **/
onMounted(async () => {
  // 解析路由的 categoryId
  if (route.query.categoryId) {
    queryParams.value.categoryId = route.query.categoryId
  }
  // 获得商品信息
  await getTabsCount()
  await getList()
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id', 'parentId')
})
</script>
<style scoped>
@import '@/styles/website.scss';
</style>
